System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

24% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Design Amazon S3
Design Google Ads
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design Discord
Image

Here is the step-by-step system design for Discord.

1. Problem Definition and Scope

We are designing a large-scale real-time communication platform organized into communities (Servers/Guilds) and channels. Unlike simple messenger apps, Discord focuses on persistent group chat for large communities (up to hundreds of thousands of users per server).

  • Main User Groups:
    • Regular Users: Join servers, chat in text channels, and see real-time presence (who is online).
    • Admins: Create servers, manage channels, and assign roles.
  • Main Actions: Sending text messages, reading message history, and receiving real-time updates.
  • Scope:
    • In Scope: Real-time Text Chat (1-on-1 and Group), Server/Channel management, Presence (Online/Offline status), and Message History.
    • Out of Scope: Voice and Video audio processing (we will handle the signaling to join a call, but not the actual media streaming), Screen Sharing, and Payments.
Image

2. Clarify functional requirements

Must Have:

  • Users can create Servers (Guilds) and Channels.

  • Users can send text messages and receive them in real-time (<100ms).

  • Users can view chat history (infinite scroll).

  • Users can see the online status of friends or guild members.

  • Messages are persistent and ordered by time.

  • Supports Unread indicators (badges).

Nice to Have:

  • "User is typing..." indicators.

  • Rich media (images/videos) in chat.

  • Push notifications for mobile devices.

Image

3. Clarify non-functional requirements

  • Target Users: 50 Million Daily Active Users (DAU).

  • Concurrent Users: ~10 Million users online at once.

  • Throughput: Extremely write-heavy (chat) and read-heavy (fan-out).

  • Latency: Real-time delivery is critical. Users expect instant communication.

  • Availability: 99.99%. The service must be always on for gamers and communities.

  • Consistency:

    • Strong Consistency: For message ordering within a channel.
    • Eventual Consistency: Acceptable for cross-device read status or presence updates.
  • Data Retention: Messages are stored forever unless deleted.

Image

4. Back of the envelope estimates

  • Traffic (QPS):
    • 50M DAU.
    • Average 20 messages per user/day = 1 Billion messages/day.
    • Write QPS: messages/sec (average).
    • Peak Write QPS:~5x average messages/sec.
    • Fan-out: If a user sends a message in a channel with 100 active listeners, that is 1 write but 100 outgoing WebSocket pushes.
  • Storage:
    • Avg message size = 100 bytes (text + metadata).

    • Daily Storage = .

    • Yearly Storage = .

    • Conclusion: We need a distributed database that allows easy horizontal scaling (adding more nodes).

  • Bandwidth:
    • Text is cheap.
    • If 10% of messages have a 500KB image: .
    • We need a CDN to offload this traffic.
Image

5. API design

We will use a Hybrid Approach: HTTP REST for actions (sending data) and WebSockets for events (receiving data).

1. REST API (Client -> Server Actions)

  • POST /channels/{channel_id}/messages
    • Request: { content: "Hello", nonce: "uuid", attachments: [...] }
    • Response: 200 OK, Message Object.
    • Why REST? It handles uploads, validation, and rate limiting easier than WebSockets.
  • GET /channels/{channel_id}/messages
    • Request: ?limit=50&before={message_id}
    • Response: List of messages.
    • Note: Uses cursor-based pagination (using message ID) for stable scrolling.
  • POST /gateway/url
    • Response: { url: "wss://gateway-3.discord.com" }
    • Purpose: Returns the best WebSocket server for the user to connect to.

2. WebSocket API (Server -> Client Real-time)

  • OpCodes (Commands):
    • IDENTIFY: Client sends auth token to log in.
    • HEARTBEAT: Client pings every 40s to say "I'm still here."
  • Events (Push):
    • MESSAGE_CREATE: New message data.
    • PRESENCE_UPDATE: User X went offline.

6. High level architecture

We separate the "Stateful" connection layer from the "Stateless" logic layer.

Components:

  1. Clients: Web, Mobile, Desktop apps.

  2. Load Balancer: Routes HTTP traffic to API servers.

  3. REST API Servers: Stateless servers that handle "Sending Messages", "Login", "Guild Management".

  4. WebSocket Gateway: Stateful servers. Each server holds ~100k open TCP connections. Their only job is to push data to users.

  5. Service Layer:

    • Chat Service: Processes messages.
    • Guild Service: Manages members and roles.
    • Presence Service: Tracks online status.
  6. Message Queue (Kafka): Connects the API layer to the Gateway layer.

  7. Databases: ScyllaDB (Messages) and PostgreSQL (Metadata).

Image

7. Data model

1. Chat Storage (Cassandra / ScyllaDB):

We need massive write throughput. Relational DBs (MySQL) struggle with billions of rows. ScyllaDB (a faster Cassandra) is perfect.

  • Table: messages
  • Partition Key: channel_id
    • Why: Keeps all messages for one channel on the same disk partition. Reading history is just scanning one partition.
  • Clustering Key: message_id (Snowflake ID)
    • Why: Sorts messages by time automatically on disk.
  • Columns: author_id, content, created_at.

2. Metadata (PostgreSQL):

For complex relationships (Users, Roles, Guild settings) where consistency matters more than raw write speed.

  • Table: users (id, username, hash)
  • Table: guilds (id, name, owner_id)
  • Table: members (guild_id, user_id, roles)

3. Snowflake IDs:

We generate unique 64-bit IDs for every message.

  • Structure: [Timestamp (41 bits)] + [Worker ID] + [Sequence]
  • Benefit: We can sort by ID to get chronological order. We don't need a separate "created_at" index.

8. Core flows end to end

We have broken this down into the three most critical operations for a chat system: Sending a Message (The Write Path), Delivering the Message (The Fan-Out), and Reading History (The Cold Read).

This level of detail shows the interviewer you understand not just what components to use, but how they talk to each other.

Flow A: Sending a Message (The "Write" Path)

This flow focuses on durability and consistency. Our goal is to accept the message, save it safely, and acknowledge the user as fast as possible.

  1. Client Request:
    • User A (in the "Gaming" server, #general channel) types "GG WP" and hits Enter.
    • The client sends a POST request to the API Load Balancer.
    • Payload: { content: "GG WP", nonce: "uuid-123", channel_id: "999" }
  2. API Server Processing:
    • The request lands on one of the stateless API Servers.
    • Auth & Rate Limit: The server validates the JWT token and checks if User A has exceeded their rate limit (using a Redis counter).
    • Logic Check: The server checks the Guild Cache (Redis) to answer: "Is User A a member of this guild?" and "Do they have permission to write in #general?"
  3. ID Generation:
    • Once validated, the API Server generates a unique 64-bit Snowflake ID.
    • This ID is critical because it contains the timestamp. This defines the exact order of the message forever.
  4. Database Commit (Persistence):
    • The API Server writes the row to ScyllaDB.
    • Partition Key: channel_id (ensures all messages for #general live together).
    • Clustering Key: message_id (ensures they are sorted by time).
    • Note: We write to the database before doing anything else to ensure data is never lost.
  5. Handoff & Response:
    • Once ScyllaDB confirms the write, the API Server does two things in parallel:
      1. Returns 200 OK to User A (User A sees the message stop "spinning" and settle).
      2. Publishes a message to the Kafka topic guild-events for asynchronous processing.
Image

Flow B: Delivering the Message (The "Fan-Out")

This is the most complex part of Discord. We need to take that single message from Flow A and push it to 100, 1,000, or 100,000 other people in real-time.

  1. The Event Trigger:
    • A Fan-Out Worker (a background service) picks up the event from the Kafka guild-events topic.
    • Event: "New message in Channel #general (ID: 999) of Guild 'Gaming' (ID: 555)."
  2. Member Discovery:
    • The worker needs to know: "Who acts receiving updates for this channel?"
    • It queries the Guild Session Cache (Redis). This is a special set that contains only the User IDs of members who are currently online.
    • Optimization: We do not care about offline users here. They will fetch the message via API when they wake up later.
  3. Routing (The "Where are they?" problem):
    • Now the worker has a list of, say, 1,000 online User IDs. It needs to find which Gateway Server holds the open WebSocket connection for each user.
    • It queries the Session Mapping (Sharded Redis).
    • Result:
      • Users 1-500 are on Gateway-Node-A.
      • Users 501-1000 are on Gateway-Node-B.
  4. The Push:
    • The Fan-Out Worker sends a lightweight RPC (Remote Procedure Call) to Gateway-Node-A and Gateway-Node-B.
    • Command: "Push this JSON payload to these specific User IDs."
  5. Delivery:
    • The Gateway Nodes receive the command. They look up the specific TCP socket for each User ID in their local memory.
    • They write the JSON frame (MESSAGE_CREATE) directly to the socket.
    • User B's Client: Receives the WebSocket frame and renders the message immediately. This usually happens in under 100ms.
Image

Flow C: Reading History (The "Cold" Read)

This flow happens when User B opens Discord on a new phone, or scrolls up to see what happened yesterday.

  1. Local Cache Check:
    • The client first checks its own local database (SQLite) on the device. If the data is there, it loads instantly.
  2. API Request:
    • If data is missing, the client requests GET /channels/999/messages?limit=50.
  3. Hot Cache Check (Server):
    • The API Server checks the Message Cache (Redis).
    • This cache holds the most recent 50-100 messages for active channels. If the channel is popular, the data is likely here, resulting in sub-millisecond return time.
  4. Database Read (Fallback):
    • If the user is scrolling far back (cold data), the cache misses.
    • The API Server queries ScyllaDB.
    • Query: SELECT * FROM messages WHERE channel_id = 999 AND message_id < {cursor_id} LIMIT 50.
    • Because ScyllaDB partitions by channel_id, this read is highly efficient (it only seeks one specific spot on the disk).
  5. Return:
    • The API returns the JSON list. The client displays it and also saves it to its local SQLite db for next time.
Image

9. Caching and read performance

Discord is read-heavy (1 message sent = 100 people reading it).

  • Guild State Cache (Redis):
    • We cache the list of members and their roles for every active guild.
    • This is critical for the "Validation" step in Flow A. We cannot query Postgres for every single message sent.
  • Message Cache (Redis):
    • We store the last 50 messages of active channels in a Redis List.
    • When a user clicks a channel, we serve from Redis (sub-millisecond).
    • If they scroll up, we fall back to ScyllaDB.
  • Client-Side Cache:
    • The Discord app itself runs a local database (SQLite). It caches messages on your device so it doesn't need to fetch them from the server every time you restart the app.

10. Storage, indexing and media

  • Primary Database: ScyllaDB (C++ rewrite of Cassandra).
    • Why? Low latency, high throughput, and fault tolerance.
  • Search Indexing:
    • ScyllaDB is bad for "text search" (e.g., "Find messages with 'apple'").
    • We use a separate Elasticsearch cluster.
    • A background worker reads the Kafka stream (from Flow B) and indexes messages into Elasticsearch.
  • Media Storage:
    • We do not store images in the database.
    • Flow: Client asks API for a signed upload URL -> Client uploads file to Amazon S3 -> Client includes the S3 URL in the message.
    • Delivery: Users download images via a CDN (Cloudflare) to ensure speed.

11. Scaling strategies

  • Gateway Partitioning (The C10K Problem):
    • One server cannot hold 10M connections.
    • We use Consistent Hashing to distribute users across hundreds of Gateway Servers.
    • If Gateway-1 fails, the users connected to it act smartly: they wait a random few seconds (Jitter) and reconnect, getting routed to Gateway-2.
  • Lazy Guilds (The "Mega Server" Problem):
    • Problem: In a server with 500k users, broadcasting "User X is online" to 499,999 others is impossible.
    • Solution: We don't. For large servers, the client only receives updates for the currently viewed channel. We do not send Presence updates (Online/Offline) for the whole member list, only for the visible viewport or friends.
  • Database Sharding:
    • ScyllaDB automatically shards data across nodes using the channel_id hash. Adding storage is as simple as adding a new node to the ring.

12. Reliability, failure handling and backpressure

  • Redundancy: All services (API, Gateway, DB) run across at least 3 Availability Zones (physical data centers).
  • Backpressure:
    • If a user tries to send 100 messages/sec, the API Gateway returns HTTP 429 (Too Many Requests).
    • If the Kafka consumers fall behind (system overloaded), we might drop "Typing Indicators" (low priority) to ensure "New Messages" (high priority) get through.
  • Idempotency:
    • Every message send attempt has a client-generated nonce (UUID).
    • If the network fails and the client retries, the server sees the same nonce and knows to ignore the duplicate.

13. Security, privacy and abuse

  • Encryption: TLS 1.3 for all connections.
  • Auth: JSON Web Tokens (JWT). The token is validated once when the WebSocket connects.
  • Safety:
    • Media Scanning: Images are processed asynchronously (PhotoDNA) to detect illegal content.
    • Malware: File attachments are scanned for viruses before being downloadable by others.
  • Privacy:
    • Note: Standard Discord servers are not End-to-End Encrypted (E2EE) because features like "Server Search", "Auto-Mod", and "Report to Trust & Safety" require the server to read messages.

14. Bottlenecks and next steps

  • Bottleneck: Presence Storms. If a major event happens (e.g., a new game release), millions of users log in simultaneously.
    • Fix: Implement aggressive rate limiting on the IDENTIFY (Login) WebSocket opcode to queue users rather than crashing the Gateways.
  • Bottleneck: Hot Partitions. A single channel (e.g., a "raid" in a popular server) getting 1000 msgs/sec.
    • Fix: Further sharding logic or "time-bucketing" within the channel partition to spread the write load.

Summary

  1. Architecture: Hybrid REST (Write) and WebSocket (Read).

  2. Storage: ScyllaDB for billions of messages, partitioned by Channel ID.

  3. Scaling: Solved "Fan-out" by using Kafka and optimizing large servers with "Lazy" loading.

  4. Gateway: Managed millions of persistent connections using consistent hashing.

Design WhatsApp
Design a Distributed Rate Limiter
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Flow A: Sending a Message (The "Write" Path)

Flow B: Delivering the Message (The "Fan-Out")

Flow C: Reading History (The "Cold" Read)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary